# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import json
import time
from datetime import datetime

import numpy as np
from dateutil.relativedelta import relativedelta
from django.http import Http404, HttpResponseRedirect
from django.shortcuts import get_object_or_404
from django.views.decorators.cache import never_cache
from wenlincms.utils.views import render

from wlapps.utils.base62 import wldecode
from wlmodels.codes.models import ELNic
from wlmodels.company.models import ELPost, ELRegion
from wlmodels.companyplus.models import ELHGEntDetail
from wlviews.lifecycle.gammafb import show
from wlviews.lifecycle.lifecycle import lifecurve
from wlviews.lifecycle.risk import risk
from wlviews.lifecycle.shcfx import shcfx
from wlviews.saas.fee import customer_verify_fee, noauth_redirct_iframe
from wlviews.saas.models import ELStatisticsLife


@never_cache
def lifecycle(request, entid):
    entid = wldecode(entid, addcrc=True)
    if not entid or entid > 500000000:
        raise Http404
    result = {}
    company = get_object_or_404(ELPost, entid=entid)
    if customer_verify_fee(request, saas_pindao="20", saas_item="51", tkey=entid):
        return HttpResponseRedirect(noauth_redirct_iframe)
    basic = company.ent_basic
    ESDATE = basic.ESDATE
    now = datetime.now().date()
    l_date = (now - ESDATE).days / 365.0 + 3
    # 企业状态分析
    tmonthlist = ELHGEntDetail.objects.filter(entid_id=company.entid).order_by('tmonth')
    scalelist = tmonthlist.values_list("scale", flat=True)
    if scalelist:
        tmonth = str(tmonthlist.first().tmonth)
        tmonth = datetime.strptime(tmonth, '%y%m').date()
        t_date = ((tmonth - ESDATE).days / 365.0 + 1) * 12
    else:
        tmonth = None
        t_date = None
    # if len(scalelist) < 3:
    #     # 查询有三年以上税务数据的税务收入
    #     id_list = ELFinanceTax.objects.filter(year='2012').values_list("id", flat=True)
    #     taxlist = ELFinanceTax.objects.filter(id__in=id_list).order_by('year').values_list("total_profit",
    #                                                                                        flat=True)
    # else:
    #     taxlist = None
    # 开业日期
    if len(scalelist) > 3 and t_date:
        companyxy, companyt = lifecurve(-t_date, scalelist)
    # elif taxlist:
    #     companyxy, companyt = lifecurve(taxlist)
    else:
        companyxy, companyt = 0, 0
    if companyxy and companyt:
        companyxy[0] = xy2date(companyxy[0], tmonth)
        companyt = xy2date(companyt, tmonth)

    # 行业及企业生存信息
    industrype = basic.INDUSTRYPHY  # 行业门类
    if industrype == 'C':
        method = 'gamma'
    elif industrype != 'C':
        method = 'weibull'
    else:
        method = None
    industryco = basic.INDUSTRYCO[:2]  # 行业代码
    INDUSTRYPHY = industrype + industryco  # 行业编码
    DOMDISTRICT = basic.DOMDISTRICT_id[:2]  # 地区
    REGCAP = basic.REGCAP or 1  # 注册资本
    if 0 < REGCAP <= 100:
        num = 1
    elif 100 < REGCAP <= 1000:
        num = 2
    elif 1000 < REGCAP:
        num = 3
    else:
        num = None

    if INDUSTRYPHY and method:
        # 查询行业
        hangye_life = ELStatisticsLife.objects.filter(INDUSTRYPHY=INDUSTRYPHY, method=method, DOMDISTRICT_id=None,
                                                      REGCAP=None).first()
        (k1, r1) = hangye_life.life_k, hangye_life.life_r
        # 行业类型编码
        industxy, industt = get_value(l_date, industrype, k1, r1)
        result['hangyed'] = zip(*industxy)
        result['hangyef'] = industt

        # 查询地区
        diqu_life = ELStatisticsLife.objects.filter(INDUSTRYPHY=INDUSTRYPHY, method=method, DOMDISTRICT_id=DOMDISTRICT,
                                                    REGCAP=None).first() or hangye_life
        (k2, r2) = diqu_life.life_k, diqu_life.life_r
        # 行业类型编码
        industxy, industt = get_value(l_date, industrype, k2, r2)
        result['diqud'] = zip(*industxy)
        result['diquf'] = industt

        # 查询资产  生命周期 生存概率
        dqiye_life = ELStatisticsLife.objects.filter(INDUSTRYPHY=INDUSTRYPHY, method=method, DOMDISTRICT_id=DOMDISTRICT,
                                                     REGCAP=num).first() or diqu_life
        (k3, r3) = dqiye_life.life_k, dqiye_life.life_r
        # 生命周期曲线 无海关数据时使用
        regcapxy, regcapt = get_value(l_date, industrype, k3, r3)
        if not companyxy and not companyt:
            companyxy = regcapxy
            companyt = regcapt
            companyxy[0] = xy2date(companyxy[0], ESDATE)
            companyt = xy2date(companyt, ESDATE)
        # 死亡概率  需要risk函数
        gld = risk(*regcapt)
        cha = int((now - ESDATE).days / 365.0 * 10)
        gld = [x[cha:cha + 30] for x in gld]
        if gld[0]:
            gld = get_max(gld)
            gld[0] = xy2date(gld[0], ESDATE)
        result['gld'] = zip(*gld)

        # 坐标点  分界点
        result['qiyed'] = zip(*companyxy)
        result['qiyef'] = companyt

        # 企业信息
        nic = ELNic.objects.filter(code=INDUSTRYPHY).first() or ELNic()
        region = ELRegion.objects.filter(level=3, code__startswith=DOMDISTRICT[:2]).first() or ELRegion()
        result['name'] = company.ENTNAME
        result['hangye'] = nic.name
        result['diqu'] = region.fulltitle

        # 注吊销时间
        the_cancel = company.c_cancel.all().first()
        if the_cancel:
            endtime = the_cancel.CANDATE
            result['endtype'] = '注'
        else:
            the_revoke = company.c_revoke.all().first()
            if the_revoke:
                endtime = the_revoke.REVDATE
                result['endtype'] = '吊'
            else:
                endtime = None
        if endtime:
            endtime = time.mktime(endtime.timetuple())
        result['endtime'] = endtime
    return render(request, "saas/lifecycle/lifecycle.html", {'result': json.dumps(result)})


def xy2date(xylist, ESDATE):
    xylist = list(xylist)
    for index, value in enumerate(xylist):
        # 根据开业日期 进行坐标转换
        year = int(value)
        month = (value - year) * 12
        delta = ESDATE + relativedelta(years=year) + relativedelta(months=int(month))
        value = time.mktime(delta.timetuple())
        xylist[index] = value
    return xylist


def get_value(l_date, code, k, r):
    l_date = 20 if l_date < 20 else int(l_date)
    if code == 'C':
        # 制造业
        industxy, industt = shcfx(l_date, k, r)
        industxy, industt1 = shcfx(l_date, industt[1], 1.3)
    else:
        # 非制造业
        industxy, industt = show(l_date, k, r)
        industxy, industt1 = show(l_date, industt[1], 1.3)
    return industxy, industt


def get_max(gld):
    index = np.argmax(gld[1])
    if index < 3:
        index = 3
    elif index > 26:
        index = 26
    gld = [gld[0][index - 2:index + 4], gld[1][index - 2:index + 4]]
    return gld
